package com.example.music.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music.R;
import com.example.music.activity.MusicActivity;
import com.example.music.adapter.SongAdapter;
import com.example.music.db.FavoritesDAO;
import com.example.music.model.AppConstants;
import com.example.music.model.Song;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FavoritesFragment extends Fragment {
    private RecyclerView recyclerView;
    private SongAdapter adapter;
    private List<Song> favoriteSongs = new ArrayList<>();
    private FavoritesDAO favoritesDao;

    @SuppressLint("MissingInflatedId")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        AppConstants.num=1;
        View view = inflater.inflate(R.layout.fragment_favorites, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        favoritesDao = new FavoritesDAO(getContext());

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        loadFavoriteSongs();
    }

    private void loadFavoriteSongs() {
        favoriteSongs.clear(); // Clear existing list before loading new data

        List<String> favoritePaths = favoritesDao.getAllFavoritePaths();

        // 从媒体库加载歌曲信息
        try (Cursor cursor = requireContext().getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Audio.Media.TITLE,
                        MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media.ALBUM,
                        MediaStore.Audio.Media.DATA,
                        MediaStore.Audio.Media.DURATION
                },
                MediaStore.Audio.Media.DATA + " IN (" + makePlaceholders(favoritePaths.size()) + ")",
                favoritePaths.toArray(new String[0]),
                null
        )) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                    String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                    String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    long duration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));

                    Song song = new Song(title, artist, album, filePath);
                    song.setDuration(duration);
                    // 获取专辑封面
                    Bitmap albumCover = getAlbumArt(filePath);
                    song.setAlbumCover(albumCover);
                    // 获取歌词文件
                    String lyricsPath = findLyricsFile(filePath);
                    song.setLyricsPath(lyricsPath);

                    favoriteSongs.add(song);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 设置Adapter
        if (adapter == null) {
            adapter = new SongAdapter(favoriteSongs);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.updateList(favoriteSongs); // Update the existing adapter's data
        }

        adapter.setOnItemClickListener(new SongAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Song song) {
                Intent intent = new Intent(requireContext(), MusicActivity.class);
                intent.putExtra("position", String.valueOf(favoriteSongs.indexOf(song)));
                intent.putExtra("songList", new ArrayList<>(favoriteSongs)); // Pass a copy of the list
                startActivity(intent);
            }
        });
    }

    private String makePlaceholders(int length) {
        if (length <= 0) {
            return ""; // 如果长度小于等于0，返回空字符串
        }
        StringBuilder sb = new StringBuilder(length * 2);
        for (int i = 0; i < length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append("?");
        }
        return sb.toString();
    }

    // 获取封面
    private Bitmap getAlbumArt(String filePath) throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            byte[] artBytes = retriever.getEmbeddedPicture();
            if (artBytes != null) {
                return BitmapFactory.decodeByteArray(artBytes, 0, artBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return null;
    }

    private String findLyricsFile(String songFilePath) {
        File songFile = new File(songFilePath);
        File directory = songFile.getParentFile();
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            return null;
        }

        FilenameFilter lrcFilter = (dir, name) -> name.equalsIgnoreCase(songFile.getName().replace(".mp3", ".lrc"));
        File[] lrcFiles = directory.listFiles(lrcFilter);

        if (lrcFiles != null && lrcFiles.length > 0) {
            return lrcFiles[0].getAbsolutePath();
        }

        return null;
    }
}



